<template>
	<div class="condition-config">
		<div v-for="(condition, index) in localConditionList" :key="index" class="condition-config-item">
			<div v-if="index != 0" class="condition-config-item-and">{{ connectorText }}</div>
			<div class="condition-config-item-title">
				<div>{{ title }}</div>
				<el-button type="text" icon="el-icon-delete" @click="deleteCondition(index)"></el-button>
			</div>
			<div class="condition-config-item-content">
				<el-cascader 
					class="conditional-config-select-max" 
					popper-class="conditional-config_cascader-popover"
					v-model="condition.toEnName" 
					:options="filedList.filter(item => condition.toEnName === item.enName || localConditionList.every(i => i.toEnName !== item.enName))" 
					placeholder="选择要过滤的字段" 
					filterable 
					:props="cascaderProps" 
					@change="handleSelectionChange(index)" 
					ref="cascaderHandle"
				>
					<template slot-scope="{ data }">
						<div class="item" :class="data.cnName.length > 12 ? 'item-overflow' : ''" :title="data.cnName">{{ data.cnName }}</div>
					</template>
				</el-cascader>
				<el-select 
					v-if="isShowOperate"
					class="conditional-config-select-small" 
					v-model="condition.operate" 
					placeholder="判断符" 
					:disabled="!condition.toEnName"
				>
					<el-option v-for="i in findData(filedList, condition.toEnName).operateList || []" :label="i.cnName" :value="i.enName" :key="i.enName"></el-option>
				</el-select>
				<el-select 
					v-if="!condition.operate || (condition.operate != 'NOT_EMPTY' && condition.operate != 'EMPTY')" 
					:class="isShowOperate ? 'conditional-config-select-small' : 'conditional-config-select-max'"  
					v-model="condition.valueType" 
					placeholder="固定值" 
					:disabled="!condition.toEnName" 
					@change="selectChangeCondition(condition, index)"
				>
					<el-option v-for="i in findData(filedList, condition.toEnName).valueTypeList || []" :label="i.cnName" :value="i.enName" :key="i.enName"></el-option>
				</el-select>
				<fixedInput
					class="conditional-config-select-max" 
					v-if="condition.valueType == '1'"
					v-model="condition.value"
					:field="findData(filedList, condition.toEnName)"
                    :operator="condition.operate"
                    @input="condition.value = $event"
				></fixedInput>
				<el-cascader 
					class="conditional-config-select-max" 
					popper-class="conditional-config_cascader-popover"
					v-if="condition.valueType == '2'" 
					v-model="condition.value[0]" 
					:options="filterAndDisableData(fromFieldList, condition.toEnName)" 
					placeholder="请选择" 
					@change="closeCascader" 
					@click.native="changeEmpty"
					filterable 
					clearable
					:props="cascaderProps" 
					ref="cascaderHandle"
				>
					<template slot-scope="{ data }">
						<div class="item" :class="data.cnName.length > 12 ? 'item-overflow' : ''" :title="data.cnName">{{ data.cnName }}</div>
					</template>
				</el-cascader>
				<ConnectorModuleRuleFormItemApp 
					class="conditional-config-select-max" 
					v-else-if="condition.valueType == '3' && condition.operate != 'NOT_EMPTY' && condition.operate != 'EMPTY'" 
					:currentToField="findData(filedList, condition.toEnName)" 
					:isDisabledFromFieldSelect="false" 
					:fromFieldList="localConditionList" 
					:fromBizTypeName="findData(filedList, condition.toEnName).cnName"
					:value="condition.value[0]" 
					@change="handleChange($event, index)" 
				/>
			</div>
			<div v-if="index === localConditionList.length - 1">
				<el-button type="text" icon="el-icon-plus" @click="addCondition">{{ addButtonText }}</el-button>
			</div>
		</div>
	</div>
</template>
  
<script>
import { matchFieldToTransform } from '@src/modules/connector/util'
import ConnectorModuleRuleFormItemApp from '@src/modules/connector/components/rule-form/item-form-app'
import fixedInput from '@src/modules/trigger/view/setting/components/trigger_condition/components/fiexdInput.vue';
import state from '@src/modules/trigger/view/setting/util/state.js';

export default {
	name: 'condition-config',
	props: {
		title: String, // 条件组的标题
		filedList: Array, // 条件数据
		fromFieldList: Array, // 选择对应字段时显示的选择框的数据
		value: Array,
		isShowOperate: { // 是否显示判断符，编辑时要修改的字段不需要判断符
			type: Boolean,
			default: true,
		},
		addButtonText: { // 添加按钮的文本
			type: String,
			default: '添加且',
		},
		connectorText: { // 连接符，默认是且
			type: String,
			default: '且',
		},
	},
	components: {
		ConnectorModuleRuleFormItemApp,
		fixedInput,
	},
	data() {
		return {
			localConditionList: JSON.parse(JSON.stringify(this.value || [])),
		};
	},
	watch: {
		// 监听 props 的变化，并更新本地副本
		value: {
			handler(newVal) {
				if (JSON.stringify(newVal) === JSON.stringify(this.localConditionList)) {
					return;
				}
				this.localConditionList = JSON.parse(JSON.stringify(newVal));
			},
			deep: true,
		},
		// 监听本地副本的变化，并同步到父组件
		localConditionList: {
			handler(newVal) {
				if (JSON.stringify(newVal) === JSON.stringify(this.value)) {
					return;
				}
				this.$emit('change', newVal);
			},
			deep: true,
		},
	},
	computed: {
		// 联级选择器的一些配置
		cascaderProps() {
			return {
				checkStrictly: true,
				label: 'cnName',
				value: 'enName',
				emitPath: false,
				expandTrigger: 'hover',
			};
		},
	},
	methods: {
		selectChangeCondition(condition, index) {
			condition.value = [];
			// 这个事件是当选择来自什么表单的字段
			this.$emit('selectChange', condition, index);
		},
		// 在列表中查询数据，返回查询到的对象
		findData(list, flg) {
  			for (const item of list) {
    			if (item.enName === flg) {
      				return item;
    			}
    			if (item.children) {
      				const result = this.findData(item.children, flg);
      				if (result.enName === flg) {
        				return result;
      				}
    			}
  			}
  			return { operateList: [], valueTypeList: [] };
		},
		handleSelectionChange(index) {
			this.closeCascader();

			// 重置operate,valueType,value，当有新的toEnName被选中时
			if (index !== undefined) {
				// 默认选中第一项
				this.localConditionList[index].operate = this.findData(this.filedList, this.localConditionList[index].toEnName).operateList?.[0]?.enName;
				this.localConditionList[index].valueType = this.findData(this.filedList, this.localConditionList[index].toEnName).valueTypeList?.[0]?.enName;
				this.localConditionList[index].value = [];
			}
		},
		closeCascader() {
			// 关闭下拉菜单
			this.$refs.cascaderHandle.map((item) => {
				item.dropDownVisible = false;
			});
		},
		// 添加条件
		addCondition() {
			this.localConditionList.push({
				toEnName: '',
				operate: '',
				valueType: '',
				value: [],
			});
		},
		// 删除条件
		deleteCondition(index) {
			if (this.localConditionList.length === 1) {
				this.localConditionList[0].toEnName = '';
				this.localConditionList[0].operate = '';
				this.localConditionList[0].valueType = '';
				this.localConditionList[0].value = [];
				return;
			}
			this.localConditionList.splice(index, 1);
		},
		filterAndDisableData(data, enName) {
			// 通过matchFieldToTransform过滤掉数组中不符合条件的元素，如果子元素有相同的则保留父元素，但设置disabled为true，禁用掉父元素，保留子元素
			// const targetFieldType = this.findData(this.filedList, enName).fieldType;
			const targetField = this.findData(this.filedList, enName);

			function filterElement(element) {
				const item = {
					...element,
					// disabled: element.fieldType !== targetFieldType,
					disabled: !matchFieldToTransform(targetField, element),
				};

				if (element.children) {
					const filteredChildren = element.children.filter(child => filterElement(child));
					if (filteredChildren.length > 0) {
						item.children = filteredChildren;
						return item;
					} else {
						delete item.children;
					}
				}
				return matchFieldToTransform(targetField, item) || item.children ? item : null;
			}
			return data.map(element => filterElement(element)).filter(element => element !== null);
		},
		changeEmpty() {
			state.parentNodeApiIdList.forEach(item => {
				// 判断有没有null
				if (item === null || item === undefined) {
					this.$nextTick(() => {
						document.querySelectorAll(".el-cascader-menu__empty-text").forEach((item) => {
							item.innerText = "请完成上级节点设置";
						});
					})
				}
			})
		},
		handleChange(value, i) {
            this.localConditionList[i].value = [JSON.stringify(value)]
        },
	},
};
</script>

<style lang="scss">
@import '@src/modules/trigger/view/setting/style/cascader.scss';

.el-cascader-node:has(.is-disabled) {
	color: #c0c4cc;
	.is-disabled {
		cursor: not-allowed;
	}	
}
</style>
  
<style lang="scss" scoped>
::v-deep .el-icon-delete {
	color: #3d3d3d;
}

::v-deep .el-icon-delete:hover {
	color: red;
}

.condition-config {
	background-color: #f9f9f9;
	border: 1px solid #e5e5e5;
	border-radius: 4px;
	padding: 16px 24px;
	&-item {
		&-and {
			width: 100%;
			height: 20px;
			margin: 8px 0;
		}

		&-title {
			height: 30px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #eeeeee;
			border-radius: 4px;
			padding: 4px 8px;

			::v-deep .el-button {
				padding: 0;
			}
		}

		&-content {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.conditional-config-select-max {
				width: 100%;
				margin-top: 8px;
			}

			.conditional-config-select-small {
				width: calc(50% - 4px);
				margin-top: 8px;
			}
		}
	}
}
</style>
  